package com.heatingcharge.controller.pay.wxpay;

import com.heatingcharge.common.util.ChargeModeEnum;
import com.heatingcharge.entity.pay.PayInfo;
import com.heatingcharge.entity.pay.WxPayBean;
import com.heatingcharge.param.ChargeInfoParam;
import com.heatingcharge.service.pay.IPayInfoService;
import com.ijpay.core.enums.SignType;
import com.ijpay.core.enums.TradeType;
import com.ijpay.core.kit.HttpKit;
import com.ijpay.core.kit.IpKit;
import com.ijpay.core.kit.WxPayKit;
import com.ijpay.wxpay.WxPayApi;
import com.ijpay.wxpay.WxPayApiConfig;
import com.ijpay.wxpay.WxPayApiConfigKit;
import com.ijpay.wxpay.model.UnifiedOrderModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/wxPay")
@Slf4j
public class WxPayController extends AbstractWxPayApiController {
    @Autowired
    WxPayBean wxPayBean;
    @Autowired
    IPayInfoService payInfoService;

    private String notifyUrl;
    private String refundNotifyUrl;

    @Override
    public WxPayApiConfig getApiConfig() {
        WxPayApiConfig apiConfig;

        try {
            apiConfig = WxPayApiConfigKit.getApiConfig(wxPayBean.getAppId());
        } catch (Exception e) {
            apiConfig = WxPayApiConfig.builder()
                    .appId(wxPayBean.getAppId())
                    .mchId(wxPayBean.getMchId())
                    .partnerKey(wxPayBean.getPartnerKey())
                    .certPath(wxPayBean.getCertPath())
                    .domain(wxPayBean.getDomain())
                    .build();
        }
        notifyUrl = apiConfig.getDomain().concat("/wxPay/payNotify");
        refundNotifyUrl = apiConfig.getDomain().concat("/wxPay/refundNotify");
        return apiConfig;
    }

    @RequestMapping(value="/pay")
    public ModelAndView index(HttpServletRequest request, ChargeInfoParam chargeInfoParam) {
        Map<String, String> map = new HashMap<>();
//        if (StringUtils.isBlank(totalFee)) {
//            return new AjaxResult().addError("支付金额不能为空");
//        }

        String ip = IpKit.getRealIp(request);
        if (StringUtils.isBlank(ip)) {
            ip = "127.0.0.1";
        }
        WxPayApiConfig wxPayApiConfig = WxPayApiConfigKit.getWxPayApiConfig();
        String str = chargeInfoParam.getOrderNo();
        log.info("str="+str);
        Map<String, String> params = UnifiedOrderModel
                .builder()
                .appid(wxPayApiConfig.getAppId())
                .mch_id(wxPayApiConfig.getMchId())
                .nonce_str(str)
                .body("4559066-最好的支付sdk")//TODO 需要修改
                .out_trade_no(str)
                .total_fee(chargeInfoParam.getActual()+"")
                .spbill_create_ip(ip)
                .notify_url(notifyUrl)
                .trade_type(TradeType.NATIVE.getTradeType())
                .build()
                .createSign(wxPayApiConfig.getPartnerKey(), SignType.HMACSHA256);

        String xmlResult = WxPayApi.pushOrder(false, params);
        Map<String, String> result = WxPayKit.xmlToMap(xmlResult);
        String qrCodeUrl = result.get("code_url");
        map.put("codeUrl",qrCodeUrl);
        map.put("orderNo",chargeInfoParam.getOrderNo());
        return new ModelAndView("wxPay",map);
    }

    /**
     * 异步通知
     */
    @RequestMapping(value = "/payNotify", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String payNotify(HttpServletRequest request) {
        String xmlMsg = HttpKit.readData(request);
       // log.info("支付通知=" + xmlMsg);
        Map<String, String> params = WxPayKit.xmlToMap(xmlMsg);

        String returnCode = params.get("return_code");

        // 注意重复通知的情况，同一订单号可能收到多次通知，请注意一定先判断订单状态
        // 注意此处签名方式需与统一下单的签名类型一致
        if (WxPayKit.verifyNotify(params, WxPayApiConfigKit.getWxPayApiConfig().getPartnerKey(), SignType.HMACSHA256)) {
            if (WxPayKit.codeIsOk(returnCode)) {
                payInfoService.disposePayResult(params, ChargeModeEnum.WXPAY.getCode());
                // 更新订单信息
                // 发送通知等
                Map<String, String> xml = new HashMap<String, String>(2);
                xml.put("return_code", "SUCCESS");
                xml.put("return_msg", "OK");
                log.info("xml="+WxPayKit.toXml(xml));
                return WxPayKit.toXml(xml);
            }
        }
        return null;
    }

    @GetMapping("/queryByOrderNo")
    @ResponseBody
    public PayInfo queryByOrderId(@RequestParam String orderNo) {
        log.info("查询支付记录...");
        return payInfoService.queryByOrderNo(orderNo);
    }
}
